<template>
  <div v-loading="loading">
    <div v-if="+relatedData.confuse_status === 3" class="empty-wrap text-left">
      <ul class="list-group">
        <li class="list-group-item">项目名称： {{ relatedData.customer_name }}</li>
        <li class="list-group-item">
          项目状态：
          <span class="text-danger">已拒绝</span>
        </li>
        <li class="list-group-item">拒绝时间： {{ relatedData.confuse_time }}</li>
        <!-- <li class="list-group-item">拒绝人：{{ relatedData.item_person_name }}</li> -->
        <li class="list-group-item">拒绝理由：{{ relatedData.confuse_des }}</li>
      </ul>
    </div>
    <div v-else>
      <table class="table table-bordered vertical-align-middle text-center">
        <colgroup>
          <col width="14%" />
          <col width="20%" />
          <col width="14%" />
          <col width="19%" />
          <col width="14%" />
          <col width="19%" />
        </colgroup>
        <tbody>
          <tr>
            <td>主体姓名</td>
            <td>{{ relatedData.customer_name || '' }}</td>
            <td>放款金额</td>
            <td>
              <!-- <span v-if="isViewMode">{{ relatedData.reply_funds }} 万元</span>
              <el-input
                v-else
                placeholder="放款金额"
                clearable
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.reply_funds"
              >
                <span slot="append">万元</span>
              </el-input> -->
              {{ relatedData.reply_funds }} 万元
            </td>
            <td>贷款期限</td>
            <td>
              <!-- <span v-if="isViewMode">{{ relatedData.months }} 月</span>
              <el-input
                v-else
                placeholder="贷款期限"
                clearable
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.months"
              >
                <span slot="append">月</span>
              </el-input> -->
              {{ relatedData.months }} 月
            </td>
          </tr>
          <tr>
            <td>担保费率</td>
            <td>{{ entrustContract.gua_rate || relatedData.gua_rate || '-' }}%</td>
            <td>保费缴纳方式</td>
            <td>{{ enumGuaFundsType[entrustContract.gua_fee_coll_type] }}</td>
            <td>已缴担保费</td>
            <td>{{ guaFee }} 元</td>
          </tr>
          <tr>
            <td>贷款利率(%)</td>
            <td :class="tdClass">
              <span v-if="isViewMode">
                {{ relatedData.load_rate || entrustContract.load_rate || '-' }}%
              </span>
              <el-input
                v-else
                v-model="editData.load_rate"
                placeholder="贷款利率"
                v-input-number="{ fixed: 4 }"
              ></el-input>
            </td>
            <td>
              <span class="text-danger" v-if="!isViewMode">*</span>
              放款时间
            </td>
            <td :class="tdClass">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(relatedData.load_date, 'yyyy年MM月dd日') }}
              </span>
              <el-date-picker
                v-else
                v-model="editData.load_date"
                :picker-options="pickerOptions"
                :clearable="false"
                type="date"
                placeholder="放款开始时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
            <td>
              <span class="text-danger" v-if="!isViewMode">*</span>
              到期时间
            </td>
            <td :class="tdClass">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(relatedData.load_end_date, 'yyyy年MM月dd日') }}
              </span>
              <el-date-picker
                v-else
                v-model="editData.load_end_date"
                :clearable="false"
                type="date"
                placeholder="放款结束时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
          </tr>

          <tr>
            <td>放款银行名称</td>
            <td colspan="5" class="text-left" :class="tdClass">
              <span v-if="isViewMode">{{ relatedData.bank_name }}</span>
              <select-org-bank
                v-else
                v-model="editData.bank_id"
                :project-type="relatedData.gua_type"
                placeholder="选择最终放款银行（用于项目统计，可输入模糊查询）"
                @select="setPublicName"
                filterable
                class="w-100"
              ></select-org-bank>
            </td>
          </tr>
          <tr>
            <td>还款计划</td>
            <td colspan="5" class="text-left">
              <div v-if="isViewMode" class="row">
                <div class="col">
                  <el-button @click="showViewRepayList">查看还款计划</el-button>
                </div>
              </div>
              <div v-else>
                <div class="d-flex align-items-center">
                  <el-button @click="showRepayList" class="ml-4">编辑还款计划</el-button>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>{{ attachTag }}</td>
            <td colspan="5" class="text-left">
              <div v-if="isViewMode">
                <div class="empty-wrap" v-if="!attachList.length">暂无附件（借据）</div>
                <attach-list v-else :attath-data="viewList" :show-label="false"></attach-list>
              </div>
              <upload-oss
                v-else
                multiple
                ref="attachUpload"
                :dir="dir"
                :file-list="attachList"
                :on-complete="handleAttachComplete"
              ></upload-oss>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="text-center" v-if="!isViewMode">
        <el-button class="btn-long" type="primary" @click="handlePass" :loading="submitLoading">
          登记
        </el-button>
        <el-button class="btn-long" type="danger" @click="handleReject" :loading="submitLoading">
          拒绝
        </el-button>
      </div>
    </div>

    <repay-plan-dialog
      @getData="getRepayList"
      :visible.sync="repayVisible"
      :query-id="queryId"
      :view-mode="isViewMode"
      :repay-funds="relatedData.reply_funds"
      ref="repay"
    ></repay-plan-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumRepayType } from '@/credit/plugins/enum'
import RepayPlanDialog from '@/credit/components/repay/RepayPlanDialog'
import { enumGuaFundsType } from '@/credit/views/county/unionProvince/components/projectApprove/index'
import { mul } from '@vimi/utils-tool'
import { attachAdapter } from '@/bank/components/attach/index'
import { deleteOss } from '@/common/api/oss'
import AttachList from '@/bank/views/business/limit/history/attach/AttachList'
import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
// 放款日期 如果三号前可选择上月，否则只能能选择当前月并在当日之前 2023.04.19 冯甫
// const pickerOptions = {
//   disabledDate(time) {
//     const date = new Date()
//     const day = date.getDate()
//     if (day <= 3) {
//       return time > date || time < new Date(date.getFullYear(), date.getMonth() - 1, 1)
//     } else {
//       return time > date || time < new Date(date.getFullYear(), date.getMonth(), 1)
//     }
//   },
// }
export default {
  components: {
    RepayPlanDialog,
    AttachList,
    SelectOrgBank,
  },
  props: {
    viewMode: { type: Boolean, default: true },
    queryId: String,
  },
  data() {
    return {
      enumGuaFundsType,
      loading: false,
      viewList: [],
      attachList: [],
      attachAready: [],
      parentTag: '放款附件',
      attachTag: '放款凭证（借据）',
      params: {
        fields: [
          'months',
          'customer_name',
          'reply_funds',
          'load_end_date',
          'load_date',
          'load_rate',
          'loan_approval_status',
          'confuse_status',
          'confuse_time',
          'confuse_des',
          'bank_type',
          'bank_name',
          'bank_id',
          'gua_type',
          'gua_fee',
        ],
      },
      tableName: 'customer_related',
      isReviewApiError: true,
      relatedData: {},
      // 还款计划
      enumRepayType,
      repayList: false,
      repayVisible: false,
      editData: {
        gua_fee: '',
        reply_funds: '',
        months: '',
        load_date: '',
        load_end_date: '',
        load_rate: '',
        bank_type: '',
        bank_name: '',
        bank_id: '',
      },
      dir: 'credit/normal/register',
      // noticeData: {}
      submitLoading: false,
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'entrustContract']),
    isViewMode() {
      return this.viewMode
    },
    tdClass() {
      return this.isViewMode ? '' : 'input-td'
    },
    isBankOrg() {
      return this.org.orgClass === 'org_bank'
    },
    repayYear() {
      return Math.ceil(+this.editData.months / 12)
    },
    hasContract() {
      return !!this.entrustContract.entrust_contract_id
    },
    guaFee() {
      return +this.entrustContract.gua_fee || this.relatedData.gua_fee || ''
    },
    repayFunds() {
      return mul(this.editData.reply_funds, 1e4)
    },
    pickerOptions() {
      return {
        disabledDate: time => {
          const date = new Date()
          // const day = date.getDate()
          // if (+(this.relatedData.loan_approval_status || '') === 3) {
          //   const loadDate = new Date(this.relatedData.load_date)
          //   return (
          //     time > new Date(loadDate.getFullYear(), loadDate.getMonth() + 1, 0) ||
          //     time < new Date(loadDate.getFullYear(), loadDate.getMonth(), 1)
          //   )
          // }
          // if (day <= 3) {
          //   return time > date || time < new Date(date.getFullYear(), date.getMonth() - 1, 1)
          // } else {
          return (
            time > new Date(date.getFullYear(), date.getMonth() + 1, 0) ||
            time < new Date(date.getFullYear(), date.getMonth() - 1, 1)
          )
          // }
        },
      }
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.params['customer_related_id.eq'] = this.queryId
        this.getData()
        this.getAttach()
        this.$nextTick(() => {
          this.$refs.repay?.getRepayList()
        })
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    setPublicName(bank) {
      this.editData.bank_type = bank.agency_type_sub || ''
      this.editData.bank_name = bank.agency_name || ''
    },
    handleReject() {
      const data = {
        loan_approval_status: 4,
        confuse_status: 3,
        confuse_time: this.$utils.dateFormat(new Date()),
        confuse_person: this.user.realName,
      }
      this.$prompt('请输入拒绝说明', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入拒绝说明' : true),
      }).then(({ value }) => {
        this.submitLoading = true
        data.confuse_des = value
        this.$api
          .updateData(this.$serviceName, 'customer_related', this.queryId, data)
          .then(() => {
            this.$message.success('已拒绝！')
            this.$emit('success', true)
            this.beforeClose()
          })
          .catch(() => this.$message.error(`提交失败，请重试！`))
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    handleAttachComplete(files) {
      const { attachAready } = this
      const addFiles = files.filter(file => !attachAready.find(it => it.attachment === file.url))
      const deleteFiles = attachAready.filter(it => !files.find(file => file.url === it.attachment))

      const promise = []
      if (files.length) {
        promise.push(
          this.$api.addBatch(
            'credit',
            'datum_customer_attachment',
            addFiles.map(it => ({
              attachment: it.url,
              attachment_type: this.attachTag,
              parent_attachment_type: this.parentTag,
              customer_related_id: this.queryId,
              file_type: 2,
              remark: it.name,
            }))
          )
        )
      }
      if (deleteFiles.length) {
        promise.push(
          this.$api.deleteData({
            table: 'datum_customer_attachment',
            id: deleteFiles.map(it => it.id).join(','),
          }),
          deleteOss(deleteFiles.map(it => it.attachment))
        )
      }
      Promise.all(promise).then(() => {
        this.getAttach()
      })
      this.registerData()
        .then(() => {
          this.$message.success('登记成功！')
          this.$emit('success', true)
          this.beforeClose()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    getAttach() {
      if (!this.queryId) {
        return
      }
      this.$api
        .getData({
          table: 'datum_customer_attachment',
          params: {
            'customer_related_id.eq': this.queryId,
            'attachment_type.eq': this.attachTag,
          },
        })
        .then(res => {
          this.attachAready = res?.data ?? []
          this.initAttach()
        })
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      Promise.all([
        this.$store.dispatch('getEntrustContract', this.queryId),
        this.$api.getData(this.$serviceName, this.tableName, this.params),
      ])
        .then(([_entrust, res]) => {
          this.relatedData = res?.data?.[0] ?? {}
          this.initContractByExist()
        })
        .finally(() => {
          this.loading = false
        })
    },
    getNotice() {
      return this.$api.getData(this.$serviceName, 'loan_notice', {
        'customer_related_id.eq': this.queryId,
      })
    },
    getRepayList(hasList) {
      this.repayList = hasList
    },
    initAttach() {
      // 附件
      this.attachList = this.attachAready.map(attachAdapter)
      this.viewList = [
        {
          tag: this.attachTag,
          attachs: this.attachList,
        },
      ]
    },
    initContractByExist() {
      if (!this.hasContract) {
        this.isReviewApiError = true
        return
      }
      this.isReviewApiError = false
      this.setByRelatedIfEmpty()
    },
    setByRelatedIfEmpty() {
      const fistRegist = +this.relatedData.loan_approval_status === 3
      const data = fistRegist ? this.relatedData : this.entrustContract
      Object.keys(this.editData).forEach(key => {
        this.editData[key] = data[key] || this.entrustContract[key] || this.relatedData[key]
      })
      if (!fistRegist) {
        this.editData.months = this.entrustContract.load_years || ''
      }
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handlePass() {
      if (this.isReviewApiError) {
        return this.$message.error('获取登记信息失败，请刷新重试！')
      }
      if (!this.repayList) {
        return this.$message.error('请先保存还款计划')
      }

      if (!this.editData.load_date) {
        return this.$message.error('请选择放款时间')
      }

      if (!this.editData.load_end_date) {
        return this.$message.error('请选择到期时间')
      }
      if (this.editData.load_end_date < this.editData.load_date) {
        return this.$message.error('到期时间不能小于等于放款时间')
      }

      this.onSave()
    },
    onSave() {
      this.$utils
        .msgbox({
          message: `确定登记?`,
          type: 'info',
          beforeClose: () => {
            this.submitLoading = true
            this.$refs.attachUpload.submit()
          },
        })
        .catch(() => this.$message.error(`登记失败，请重试！`))
    },
    registerData() {
      const data = {
        ...this.editData,
        loan_approval_status: 3,
      }
      return this.$api.updateData(this.$serviceName, 'customer_related', this.queryId, data)
    },

    // 还款计划
    showViewRepayList() {
      this.repayVisible = true
    },

    showRepayList() {
      this.repayVisible = true
    },
    onRepayClose() {
      this.repayVisible = false
    },
    getSums(list) {
      let [capitalSum, interestSum] = [0, 0]
      for (const item of list) {
        const capital = Number.parseFloat(item.capital)
        capitalSum += isNaN(capital) ? 0 : capital

        const interest = Number.parseFloat(item.interest)
        interestSum += isNaN(interest) ? 0 : interest
      }
      return [Math.round(capitalSum * 1e2) / 1e2, Math.round(interestSum * 1e2) / 1e2]
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.input-td /deep/ .el-input-group__append {
  background-color: #ffe;
  border: none;
}
.input-td {
  background-color: #ffffee;
}
</style>
